
var constants = require("./constants");

let log = require('cf-nodejs-logging-support');
log.setLoggingLevel("info");


function checkField(array,object)
{
  if(array.length>0)
  {
    var result = true;
      array.map(
          (one)=>{
            if(!object.hasOwnProperty(one))
            {
              result=false;
            }
          }
      );
      return result;
  }else{
    return true;
  }
}


function checkEmpty(array, data) {
  let undefinedColumn = [];
  let emptyColumn = [];
  let noUndefined = true;
  let noEmpty = true;
  for (var i in array) {
    if (!data.hasOwnProperty(array[i])) {
      undefinedColumn.push(array[i]);
      noUndefined = false;
    } else if (typeof (data[array[i]]) == "string") {
      if (data[array[i]].replace(/(^\s*)|(\s*$)/g, "") == "") {
        emptyColumn.push(array[i]);
        noEmpty = false;
      }
    }
  }
  let msg = "";
  if (noUndefined && noEmpty) {
    msg = "OK"
  }
  if (!noUndefined) {
    msg = "以下字段没有赋值: "
    for (var i in undefinedColumn) {
      msg += [undefinedColumn[i]];
      msg += "  ";
    }
  }
  if (!noEmpty) {
    msg += "以下字段是空值: "
    for (var i in emptyColumn) {
      msg += [emptyColumn[i]];
      msg += "  ";
    }
  }
  return { noEmpty, noUndefined, msg };
}
function checkProperty(array, data) {
  for (var i = 0; i < array.length; i++) {
    if (!data.hasOwnProperty(array[i])) {
      data[array[i]] = "initial"
    } else {
      if (data[array[i]] == "" || data[array[i]] == " ") {
        data[array[i]] = "initial"
      }
    }
  }
}
function checkAuth(user, requiredAuth) {
  if (!user) {
    return {
      authCheck: false,
      admin: false
    }
  }
  if (user.origin) {
    // from jiangdu URL
    if (user.origin == constants.iasURL) {
      var userResult = {
        authCheck: true,
        user_id: user.user_name,
        user_name: user.given_name + " " + user.family_name,
        admin: true,
      }
      //check authorization 
      return userResult;
    }
    //return false 
    return {
      authCheck: false,
      admin: false
    }
  } else {
    // local roles
    try {
      var roles = []
      if (user.role != null) {
        user.role = user.role.replace(/'/g, "\"")
        roles = JSON.parse(user.role);
      }
    } catch (error) {
      log.error(error);
      roles = [];
    }
    var userResult = {
      authCheck: false,
      user_id: user._id,
      user_name: user.name,
      level: user.level,
      company: user.company,
      admin: false
    }
    if (roles.length > 0) {
      roles.map(role => {
        if (role == constants.ADMINAUTH) {
          userResult.admin = true;
          userResult.authCheck = true;
        }
        if (role == requiredAuth) {
          userResult.authCheck = true;
        }
      })
    }
    if (requiredAuth == constants.BASICAUTH) {
      userResult.authCheck = true;
    }
    return userResult;

  }


}
module.exports = {
  checkEmpty,
  checkProperty,
  checkAuth,
  checkField
}